<template>
  <basic-dialog
    width="60%"
    title="关联商品"
    :visible="visible"
    :showFooter="false"
    :showClose="false"
  >
    <basic-form
      ref="formData"
      isBtnBarSingleRow
      :isScalingBtn="false"
      :hasQueryPermission="false"
      :formColumns="formItems"
      :dataSource="formData"
      :handleSearchForm="handleQueryForm"
      @getFormData="getFormData"
    >
      <BtnRender slot="extensionActions" :render="renderBtnsBar" />
    </basic-form>
    <el-tabs v-model="tabs.current" @tab-click="handleSwitchTabs">
      <el-tab-pane label="已关联" :name="tabs.nameList[1]" :disabled="TableInfo.loading"></el-tab-pane>
      <el-tab-pane label="未关联" :name="tabs.nameList[0]" :disabled="TableInfo.loading"></el-tab-pane>
    </el-tabs>
    <SkusTable
      :showPagination="!seniorLinked.isSenior"
      :dataSource="TableInfo.list"
      :columns="TableInfo.columns"
      :loading="TableInfo.loading"
      :selectionChange="TableInfo.setSelection"
      :total="pagination.total"
      :pageSizes="pageSizes"
      :pagination="pagination"
      @pageChange="handlePageChange"
      @pageSizeSelect="handlePageSizeChange"
    />
    <!-- 高级关联 -->
    <SeniorLinkedDialog
      ref="seniorRef"
      :visible.sync="seniorLinked.visible"
      :columns="seniorLinked.columns"
      :dataSource="seniorLinked.dataSource"
      @seniorSearchResult="updateTableListBySeniorLinked"
    />
  </basic-dialog>
</template>
<script>
import BasicDialog from '@/components/BasicDialog';
import BasicForm from '@/components/BasicForm';
import SkusTable from '@/components/skusTable';
import BtnRender from '@/components/JSXRender/BtnRender';
import SeniorLinkedDialog from '@/components/SeniorLinkedDialog';
import {
  getInitFormData,
  TableInfo,
} from '@/utils/getUtils';
import { isResponseSuccess } from '@/utils/bizUtils';
import { getListPageBtnsBar } from '@/utils/getBtnsRender';
import skusPage from '@/mixins/commodity/skusPage';
import {
  FORM_ITEMS,
  TABLE_COLUMNS,
  TABS_ENUMS,
  TABLE_COLUMNS_V01,
} from './constants';

import {
  getNotRelByCondition,
  getRelByCondition,
  createRelateService,
  deleteRelateService
} from '@/api/commodity/commodityManage/productTagManage'
import { RuleEnum } from '../../constants/enum';
export default {
  mixins: [skusPage],
  components: {
    BasicDialog,
    BasicForm,
    SkusTable,
    BtnRender,
    SeniorLinkedDialog
  },
  props: {
    // 弹框开关
    visible: {
      type: Boolean,
      default: false
    },
    // 标签uuid
    labelUuid: {
      type: String | Number,
      default: ''
    },
    // 规则类型
    ruleType: {
      type: Number,
      default: null
    }
  },
  data () {
    return {
      allCheck: false,
      formItems: FORM_ITEMS,
      formData: getInitFormData(FORM_ITEMS),
      tabs: {
        current: TABS_ENUMS.Associated, // 当前tabs页签
        nameList: [TABS_ENUMS.NotAssociated, TABS_ENUMS.Associated] // tabs页签key集合
      },
      TableInfo: new TableInfo(),
      seniorLinked: {
        visible: false,
        columns: [{ label: 'SKU编码', prop: 'skuNo', type: 'textarea' }],
        dataSource: [{ skuNo: '' }],
        isSenior: false, // 是否是高级关联查询
      },
      btnLoading: {
        submit: false
      }
    }
  },
  watch: {
    visible (val) {
      val && this.handleQueryForm()
      val && this.TableInfo.setColumns(this.getRerenderColumns())
    },
  },
  computed: {
    // 是已关联
    isLinked () {
      return this.tabs.current == this.tabs.nameList[1]
    },
  },
  methods: {
    // 渲染按钮操作栏
    renderBtnsBar (h) {
      const btnList = [
        {
          label: '高级关联',
          method: this.handleSeniorLinked,
        },
        {
          label: '确定',
          method: this.handleEnsure,
          loading: this.btnLoading.submit
        },
        {
          label: '取消',
          method: this.handleClose,
          type: 'default'
        }
      ]
      return getListPageBtnsBar(h, btnList)
    },
    // 更新表格数据
    async updateTableList (data, requestService, isSelected) {
      const res = await requestService(data, this.TableInfo.setLoading)
      const results = res?.retData?.results ?? []
      this.TableInfo.setList(results.length == 0 ? [] : results.map(item => ({
        ...item,
        isSelected
      })))
      this.setTotalNum(res?.retData?.totalNum)
      this.allCheck = this.TableInfo.list.every(item => item.isSelected)
    },
    // 更新表格集合数据 by 高级查询
    updateTableListBySeniorLinked (skuNoList) {
      this.seniorLinked.isSenior = true
      const data = {
        labelUuid: this.labelUuid,
        skuNoList,
        pageShow: 5000,
      }
      this.tabs.current = TABS_ENUMS.NotAssociated
      this.$refs.formData.handleResetForm()
      this.updateTableList(data, getNotRelByCondition, true) // 查询未关联数据，默认勾选
    },
    // 获取表格数据
    getTableData () {
      this.seniorLinked.isSenior = false
      const data = {
        labelUuid: this.labelUuid,
        ...this.paginationParams,
        ...this.formData
      }
      this.isLinked
        ? this.updateTableList(data, getRelByCondition, true) // 更新已关联数据
        : this.updateTableList(data, getNotRelByCondition, false) // 更新未关联数据
    },
    // 切换tabs
    handleSwitchTabs () {
      this.getTableData() // 重新加载表格数据
    },
    handleCheckAll (val) {
      const updateList = this.TableInfo.list.map(item => ({
        ...item,
        isSelected: val
      }))
      this.TableInfo.setList(updateList)
    },
    // 高级关联
    handleSeniorLinked () {
      this.seniorLinked.visible = true
    },
    // 返回表单（确定）
    async handleEnsure () {
      const requestFn = this.isLinked ? deleteRelateService : createRelateService
      const skuNos = this.TableInfo.list
        .filter(item => this.isLinked ? !item.isSelected : item.isSelected)
        .map(item => item.skuNo)
      const data = {
        labelUuid: this.labelUuid,
        skuNos: skuNos
      }
      const loadingFn = state => { this.btnLoading.submit = state }
      const res = await requestFn(data, loadingFn)
      if (isResponseSuccess(res)) {
        this.$message.success('提交成功')
        this.resetState()
        this.handleClose()
      }
    },
    // 取消
    handleClose () {
      this.$emit('update:visible', false)
    },
    // 重置状态
    resetState () {
      this.tabs.current = TABS_ENUMS.Associated
      this.TableInfo.setList([])
      this.resetPageInfo() // 重置分页信息
      this.$refs.seniorRef.handleClearAll()
    },
    // 重新渲染表格列
    getRerenderColumns () {
      // 默认表格列
      let columns = TABLE_COLUMNS
      // 如果当前规则是鑫币或者积分，则渲染不同的表格列
      if ([RuleEnum.XCoin, RuleEnum.Integral].includes(this.ruleType)) {
        columns = TABLE_COLUMNS_V01
      }
      return [
        ...columns,
        {
          headerRender: h => <el-checkbox v-model={ this.allCheck } onChange={val => this.handleCheckAll(val)} />,
          render: (h, { row }) => <el-checkbox v-model={ row.isSelected } />
        }
      ]
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .total-container {
  height: 30px;
}
</style>
